﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using SlamCms.SharePoint.Core;

namespace SlamCms.SharePoint.UtilityPages
{
	public partial class UpgradeSlamFields : LayoutsPageBase
	{
		protected override void OnInit(EventArgs e)
		{
			btnUpdate.Click += new EventHandler(btnUpdate_Click);
			base.OnInit(e);
		}

		protected void Page_Load(object sender, EventArgs e)
		{	
		}

		void btnUpdate_Click(object sender, EventArgs e)
		{
			try
			{
				SlamCmsContext.SharePoint.Monitor("Upgrade SlamCMS Fields").SiteCollection(sc =>
				{
					for (int k = 0; k < sc.AllWebs.Count; k++)
					{
						SPWeb web = sc.AllWebs[k];
						for (int i = 0; i < web.Fields.Count; i++)
						{
							SPField field = web.Fields[i];

							if (field.TypeAsString.Equals("SlamCMS Field", StringComparison.OrdinalIgnoreCase))
							{
								field.SchemaXml = field.SchemaXml.Replace("SlamCMS Field", "Slam Field");
								web.AllowUnsafeUpdates = true;
								field.Update(true);
							}
						}

						for (int j = 0; j < web.Lists.Count; j++)
						{
							SPList list = web.Lists[j];

							for (int i = 0; i < list.Fields.Count; i++)
							{
								SPField field = list.Fields[i];
								if (field.TypeAsString.Equals("SlamCMS Field", StringComparison.OrdinalIgnoreCase))
								{
									field.SchemaXml = field.SchemaXml.Replace("SlamCMS Field", "Slam Field");
									web.AllowUnsafeUpdates = true;
									field.Update(true);
								}
							}
						}
						web.Dispose();
					}
				});
			}
			catch (Exception ex)
			{
				messages.Text = ex.ToString();
			}
		}
	}
}
